package admin

import (
	"encoding/json"
	"github.com/beego/beego/v2/adapter/cache"
	captcha2 "github.com/beego/beego/v2/adapter/utils/captcha"
	"go-cmdb/models"
	"go-cmdb/pkg"
)

// 全局验证码结构体
var captcha *captcha2.Captcha

// init函数初始化captcha
func init() {
	// 验证码功能
	// 使用Beego缓存存储验证码数据
	store := cache.NewMemoryCache()
	// 创建验证码
	captcha = captcha2.NewWithFilter("/captcha", store)
	// 设置验证码长度
	captcha.ChallengeNums = 4
	// 设置验证码模板高度
	captcha.StdHeight = 50
	// 设置验证码模板宽度
	captcha.StdWidth = 120

}

func (ctrl *LoginController) Prepare() {

	ctrl.AllowAnonymous(func(act string) bool {
		return true
	})

	ctrl.AdminController.Prepare()

	ctrl.IgnoreLayout(func(act string) bool {
		return true
	})
}

type LoginController struct {
	AdminController
}

func NewLoginController() *LoginController {
	ctrl := &LoginController{}

	return ctrl
}
func (ctrl *LoginController) Login() {

	ctrl.View()
	return

}

type DoLoginReq struct {
	CaptchaID string `json:"captcha_id"`
	Captcha   string `json:"captcha"`
	UserName  string `json:"user_name"`
	Password  string `json:"password"`
}

func (ctrl *LoginController) DoLogin() {

	//
	var req DoLoginReq

	if err := json.Unmarshal(ctrl.Ctx.Input.RequestBody, &req); err != nil {
		ctrl.ERROR(err.Error())
		return
	}

	//检验
	if ok := captcha.Verify(req.CaptchaID, req.Captcha); !ok {
		ctrl.ERROR("验证码不匹配")
		return
	}

	//验证数据库
	admin := models.NewUser()
	req.Password = pkg.FormatPwd(req.Password)
	curUser, err := admin.FinUser(req.UserName, req.Password)
	if curUser == nil || curUser.Status == 0 {
		if err != nil {
			ctrl.ERROR(err.Error())
			return
		}
		ctrl.ERROR("账号密码不匹配或用户不存在")
		return
	}

	if curUser.Status == 2 {
		ctrl.ERROR("该账号已被停用")
		return
	}

	//登录授权
	_ = ctrl.SetAuthUser(&AdminAuthInfo{
		UserID: curUser.ID,
	})

	ctrl.OK(nil)
	return

}

func (ctrl *LoginController) Logout() {
	//清除授权信息
	_ = ctrl.DelAuthUser()
	ctrl.Redirect(ctrl.IndexRouter(), 301)
	return
}
